#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<signal.h>

static int acceptSock=0;
static int sock=0;
void func(int signal)
{
    close(sock);
    close(acceptSock);
    raise(SIGINT);  //停止
}

int main(int argc, char *argv[])
{
    signal(SIGTSTP,func);   //先中断,再进入func函数里关闭套接字,最后再停止进程
    if(argc!=3)
    {
        printf("invalid numbers!\n");
        return -1;
    }
    sock=socket(AF_INET,SOCK_STREAM,0);  //tcp的套接字获取方式
    if(sock<0)
    {
        perror("socket:");
    }

    int isUse=1;
    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&isUse,4);

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(atoi(argv[2]));
    addr.sin_addr.s_addr=inet_addr(argv[1]);
    if(bind(sock,(struct sockaddr *)&addr,sizeof(addr))!=0)
    {
        perror("bind:");
        return -1;
    }

    if(listen(sock,10)!=0)
    {
        perror("listen:");
        return -1;
    }
    
    struct sockaddr_in ClientAddr;
    socklen_t len;
    acceptSock = accept(sock,(struct sockaddr *)&ClientAddr,&len);
    if(acceptSock<0)
    {
        perror("accept:");
        return -1;
    }
    printf("addr:%s  port:%d\n",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port));
   
    while(1)
    {
        char temp[100]={0};
        if(recv(acceptSock,temp,100,0)<0)
        {
            perror("recv:");
        }
        printf("recv:%s\n",temp);
    }
    return 0;
}